package com.ozo.boot.auth.token;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.ozo.boot.auth.log.LoginLogEvent;
import com.ozo.boot.auth.log.LoginLogUtil;
import com.ozo.boot.common.base.model.LoginUser;
import com.ozo.boot.common.base.model.ResultVO;
import com.ozo.boot.common.satoken.context.UserLoginHelper;
import com.ozo.boot.manage.pojo.vo.SysUserInfoVO;

/**
 * <p>
 * token生成器抽象类
 * </p>
 *
 * @author qiangesoft
 * @since 2024-07-11
 */
public abstract class AbstractTokenGranter implements TokenGranter {

    public LoginUser doLogin(SysUserInfoVO sysUserVO, Boolean rememberMe) {
        try {
            // 登录
            LoginUser loginUser = new LoginUser();
            loginUser.setUserId(sysUserVO.getId());
            loginUser.setUsername(sysUserVO.getUsername());
            loginUser.setDeptId(sysUserVO.getDeptId());
            loginUser.setDeptName(sysUserVO.getDeptName());
            loginUser.setMobile(sysUserVO.getMobile());
            loginUser.setNickname(sysUserVO.getNickname());
            loginUser.setRealName(sysUserVO.getRealName());
            loginUser.setGender(sysUserVO.getGender());
            loginUser.setAvatar(sysUserVO.getAvatar());
            loginUser.setRoles(sysUserVO.getRoles());
            loginUser.setPermissions(sysUserVO.getPermissions());
            loginUser.setPermissions(sysUserVO.getPermissions());
            loginUser.setRememberMe(rememberMe);
            UserLoginHelper.login(loginUser, null);

            // 获取token
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            loginUser.setAccessToken(tokenInfo.getTokenValue());
            loginUser.setExpires(tokenInfo.getTokenTimeout());

            // 长token
//            String refreshToken = SaTempUtil.createToken(loginUser.getUserId(), 2592000);
//            loginUser.setRefreshToken(refreshToken);

            SpringUtil.publishEvent(new LoginLogEvent(LoginLogUtil.success(sysUserVO.getUsername(), JSONUtil.toJsonStr(ResultVO.success()))));
            return loginUser;
        } catch (Exception e) {
            SpringUtil.publishEvent(new LoginLogEvent(LoginLogUtil.fail(sysUserVO.getUsername(), JSONUtil.toJsonStr(ResultVO.fail()))));
            e.printStackTrace();
            throw e;
        }
    }

}
